package com.cloud.config.quartzConfig;

import com.cloud.config.druidConfig.DruidConfig;
import com.cloud.constant.SystemConstant;
import com.cloud.listener.TaskListener;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.Properties;

@Configuration
public class QuartzConfig {
    @Autowired
    private SpringBeanFactory springBeanFactory;
    @Autowired
    private DruidConfig druidConfig;

    @Bean
    public SchedulerFactoryBean factoryBean() throws Exception {
        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
        factoryBean.setDataSource(druidConfig.dataSource());
        factoryBean.setJobFactory(springBeanFactory);
        factoryBean.setSchedulerName(SystemConstant.SCHED_NAME);
        factoryBean.setAutoStartup(true);
        factoryBean.setQuartzProperties(properties());
        //factoryBean.setTransactionManager(transactionManager());
        return factoryBean;
    }

    @Bean
    public Properties properties() throws Exception {
        PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();
        factoryBean.setLocation(new ClassPathResource("quartz.properties"));
        factoryBean.afterPropertiesSet();
        return factoryBean.getObject();
    }

  /*  @Bean
    public PlatformTransactionManager transactionManager() throws Exception {
        return new DataSourceTransactionManager(druidConfig.dataSource());
    }*/

    @Bean
    public Scheduler scheduler() throws Exception {
        Scheduler scheduler = factoryBean().getScheduler();
        scheduler.getListenerManager().addJobListener(taskListener());
        return scheduler;
    }

    @Bean
    public TaskListener taskListener() {
        return new TaskListener();
    }

}
